package com.casstime.ec.cloud.meeting.web.util;

import java.io.IOException;

import com.fasterxml.jackson.core.JsonGenerationException;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;

import lombok.extern.log4j.Log4j2;

/**
 * 
 * ClassName: JsonUtil Function: json封装工具，用来做jackson的封装，减少new对象的开销 Reason: ADD
 * REASON(可选).
 * 
 * @author caiguoda 2017年8月4日 上午10:29:40
 * @version
 * @since JDK 1.8
 */
@Log4j2
public class JsonUtil {
	private ObjectMapper mapper = null;

	private static class Loader {
		private static final JsonUtil INSTANCE = new JsonUtil();
	}

	public static JsonUtil getInstance() {
		return Loader.INSTANCE;
	}

	public String writeJson(Object entity) {
		String str = "";
		try {
			str = mapper.disableDefaultTyping().writeValueAsString(entity);
		} catch (JsonGenerationException e) {
			log.error("转换失败", e);
		} catch (JsonProcessingException e) {
			log.error("转换失败", e);
		}
		return str;
	}

	public <T> T readJson(String jsonStr, Class<T> t) {
		T obj = null;
		try {
			obj = mapper.readValue(jsonStr, t);
		} catch (JsonGenerationException e) {
			log.error("转换失败", e);
		} catch (JsonParseException e) {
			log.error("转换失败", e);
		} catch (JsonMappingException e) {
			log.error("转换失败", e);
		} catch (IOException e) {
			log.error("转换失败", e);
		}
		return obj;
	}

	@SuppressWarnings({ "rawtypes", "unchecked" })
	public <T> T readValue(String content, TypeReference valueTypeRef) {
		T result = null;
		try {
			result = (T) mapper.readValue(content, valueTypeRef);
		} catch (Exception e) {
			log.error("转换失败", e);

		}
		return result;
	}

}